
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;


/**
 * @author nextor
 */
public class ListFiles extends MIDlet implements CommandListener,ItemCommandListener,Runnable {
    
    private boolean midletPaused = false;
    String SEPARATOR  = System.getProperty("file.separator");
//<editor-fold defaultstate="collapsed" desc=" Generated Fields ">//GEN-BEGIN:|fields|0|
    private Form form;
    private Form selectFileSystem;
    private Command backCommand;
    private Command okCommand;
//</editor-fold>//GEN-END:|fields|0|
    private String fileSystem;
   Vector files = new Vector();
    private StreamConnectionNotifier scn;
    Vector connections = new Vector();
    Vector filepool = new Vector();
    int threadCounter = 0;
    Vector images = new Vector();
    /**
     * The ListFiles constructor.
     */
    public ListFiles() {
    }

//<editor-fold defaultstate="collapsed" desc=" Generated Methods ">//GEN-BEGIN:|methods|0|
//</editor-fold>//GEN-END:|methods|0|
//<editor-fold defaultstate="collapsed" desc=" Generated Method: initialize ">//GEN-BEGIN:|0-initialize|0|0-preInitialize
    /**
     * Initializes the application. It is called only once when the MIDlet is
     * started. The method is called before the
     * <code>startMIDlet</code> method.
     */
    private void initialize() {//GEN-END:|0-initialize|0|0-preInitialize
        // write pre-initialize user code here
//GEN-LINE:|0-initialize|1|0-postInitialize
        // write post-initialize user code here
    }//GEN-BEGIN:|0-initialize|2|
//</editor-fold>//GEN-END:|0-initialize|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: startMIDlet ">//GEN-BEGIN:|3-startMIDlet|0|3-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Started point.
     */
    public void startMIDlet() {//GEN-END:|3-startMIDlet|0|3-preAction
        // write pre-action user code here
        switchDisplayable(null, getSelectFileSystem());//GEN-LINE:|3-startMIDlet|1|3-postAction
        // write post-action user code here
    }//GEN-BEGIN:|3-startMIDlet|2|
//</editor-fold>//GEN-END:|3-startMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: resumeMIDlet ">//GEN-BEGIN:|4-resumeMIDlet|0|4-preAction
    /**
     * Performs an action assigned to the Mobile Device - MIDlet Resumed point.
     */
    public void resumeMIDlet() {//GEN-END:|4-resumeMIDlet|0|4-preAction
        // write pre-action user code here
//GEN-LINE:|4-resumeMIDlet|1|4-postAction
        // write post-action user code here
    }//GEN-BEGIN:|4-resumeMIDlet|2|
//</editor-fold>//GEN-END:|4-resumeMIDlet|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: switchDisplayable ">//GEN-BEGIN:|5-switchDisplayable|0|5-preSwitch
    /**
     * Switches a current displayable in a display. The
     * <code>display</code> instance is taken from
     * <code>getDisplay</code> method. This method is used by all actions in the
     * design for switching displayable.
     *
     * @param alert the Alert which is temporarily set to the display; if
     * <code>null</code>, then
     * <code>nextDisplayable</code> is set immediately
     * @param nextDisplayable the Displayable to be set
     */
    public void switchDisplayable(Alert alert, Displayable nextDisplayable) {//GEN-END:|5-switchDisplayable|0|5-preSwitch
        // write pre-switch user code here
        Display display = getDisplay();//GEN-BEGIN:|5-switchDisplayable|1|5-postSwitch
        if (alert == null) {
            display.setCurrent(nextDisplayable);
        } else {
            display.setCurrent(alert, nextDisplayable);
        }//GEN-END:|5-switchDisplayable|1|5-postSwitch
        // write post-switch user code here
    }//GEN-BEGIN:|5-switchDisplayable|2|
//</editor-fold>//GEN-END:|5-switchDisplayable|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: form ">//GEN-BEGIN:|14-getter|0|14-preInit
    /**
     * Returns an initialized instance of form component.
     *
     * @return the initialized component instance
     */
    public Form getForm() {
        if (form == null) {//GEN-END:|14-getter|0|14-preInit
            // write pre-init user code here
            form = new Form("form");//GEN-BEGIN:|14-getter|1|14-postInit
            form.addCommand(getBackCommand());
            form.setCommandListener(this);//GEN-END:|14-getter|1|14-postInit
            // write post-init user code here
        }//GEN-BEGIN:|14-getter|2|
        return form;
    }
//</editor-fold>//GEN-END:|14-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Method: commandAction for Displayables ">//GEN-BEGIN:|7-commandAction|0|7-preCommandAction
    /**
     * Called by a system to indicated that a command has been invoked on a
     * particular displayable.
     *
     * @param command the Command that was invoked
     * @param displayable the Displayable where the command was invoked
     */
    public void commandAction(Command command, Displayable displayable) {//GEN-END:|7-commandAction|0|7-preCommandAction
        // write pre-action user code here
        if (displayable == form) {//GEN-BEGIN:|7-commandAction|1|18-preAction
            if (command == backCommand) {//GEN-END:|7-commandAction|1|18-preAction
                // write pre-action user code here
//GEN-LINE:|7-commandAction|2|18-postAction
                // write post-action user code here
            }//GEN-BEGIN:|7-commandAction|3|7-postCommandAction
        }//GEN-END:|7-commandAction|3|7-postCommandAction
        // write post-action user code here
    }//GEN-BEGIN:|7-commandAction|4|
//</editor-fold>//GEN-END:|7-commandAction|4|


//<editor-fold defaultstate="collapsed" desc=" Generated Getter: selectFileSystem ">//GEN-BEGIN:|16-getter|0|16-preInit
    /**
     * Returns an initialized instance of selectFileSystem component.
     *
     * @return the initialized component instance
     */
    public Form getSelectFileSystem() {
        if (selectFileSystem == null) {//GEN-END:|16-getter|0|16-preInit
            // write pre-init user code here
            selectFileSystem = new Form("form1");//GEN-LINE:|16-getter|1|16-postInit
            // write post-init user code here
            System.out.println("Form 1");
         Enumeration drives = FileSystemRegistry.listRoots();
        while (drives.hasMoreElements()) {
            String driveString = drives.nextElement().toString();
            System.out.println(""+driveString);
            if(driveString!=null)
            {
                StringItem it = new StringItem(driveString,""+driveString);
                selectFileSystem.append(it);
                it.addCommand(this.getOkCommand());
                it.setItemCommandListener(this);
            }
        }
            
        }//GEN-BEGIN:|16-getter|2|
        return selectFileSystem;
    }
//</editor-fold>//GEN-END:|16-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: backCommand ">//GEN-BEGIN:|17-getter|0|17-preInit
    /**
     * Returns an initialized instance of backCommand component.
     *
     * @return the initialized component instance
     */
    public Command getBackCommand() {
        if (backCommand == null) {//GEN-END:|17-getter|0|17-preInit
            // write pre-init user code here
            backCommand = new Command("Back", Command.BACK, 0);//GEN-LINE:|17-getter|1|17-postInit
            // write post-init user code here
        }//GEN-BEGIN:|17-getter|2|
        return backCommand;
    }
//</editor-fold>//GEN-END:|17-getter|2|

//<editor-fold defaultstate="collapsed" desc=" Generated Getter: okCommand ">//GEN-BEGIN:|19-getter|0|19-preInit
    /**
     * Returns an initialized instance of okCommand component.
     *
     * @return the initialized component instance
     */
    public Command getOkCommand() {
        if (okCommand == null) {//GEN-END:|19-getter|0|19-preInit
            // write pre-init user code here
            okCommand = new Command("Ok", Command.OK, 0);//GEN-LINE:|19-getter|1|19-postInit
            // write post-init user code here
        }//GEN-BEGIN:|19-getter|2|
        return okCommand;
    }
//</editor-fold>//GEN-END:|19-getter|2|

    /**
     * Returns a display instance.
     *
     * @return the display instance.
     */
    public Display getDisplay() {
        return Display.getDisplay(this);
    }

    /**
     * Exits MIDlet.
     */
    public void exitMIDlet() {
        switchDisplayable(null, null);
        destroyApp(true);
        notifyDestroyed();
    }

    /**
     * Called when MIDlet is started. Checks whether the MIDlet have been
     * already started and initialize/starts or resumes the MIDlet.
     */
    public void startApp() {
        if (midletPaused) {
            resumeMIDlet();
        } else {
            initialize();
            startMIDlet();
        }
        midletPaused = false;
    }

    /**
     * Called when MIDlet is paused.
     */
    public void pauseApp() {
        midletPaused = true;
    }

    /**
     * Called to signal the MIDlet to terminate.
     *
     * @param unconditional if true, then the MIDlet has to be unconditionally
     * terminated and all resources has to be released.
     */
    public void destroyApp(boolean unconditional) {
    }

    protected void setFileList(String path) {


        //Opens a file connection in READ mode
        //  
        String filename;

        Vector paths = new Vector();
        paths.addElement("file:///" + path);
        int counter = 0;
        FileConnection fc = null;
        FileConnection sc = null;
        while (!paths.isEmpty()) {
            path = (String) paths.elementAt(0);
            paths.removeElement(path);
            try {
             //   a += "Opening directory " + path + "\n";
                System.out.println("Print primary path\n" + path + "\n");
                fc = (FileConnection) Connector.open(path, Connector.READ);
                Enumeration filelist = fc.list();
                sc = null;
                while (filelist.hasMoreElements()) {
                    filename =  filelist.nextElement().toString();
                    try {
                        sc = (FileConnection) Connector.open(fc.getURL() + filename, Connector.READ);
                        if (sc.isDirectory() || filename.endsWith("/")) { //checks if fc is a directory
                            paths.addElement(sc.getURL());
                         //   System.out.println("Print directory filename " + filename);
                         //   System.out.println("Print directory path "+sc.getURL());
                         //   a += "Adding directory " + filename + "\n";
                        } else if(filename.endsWith("mp3"))
                        {
                            counter++;
                            files.addElement(sc.getURL());

                        }
                        else if( filename.endsWith("JPG") || filename.endsWith("jpg"))
                        {
                            images.addElement(sc.getURL());
                        }
                            
                    } catch (IllegalArgumentException iae) {
                    }finally
                    {
                        try
                        {
                            sc.close();
                        }
                        catch(Exception e)
                        {
                            
                        }
                    }
                }
                fc.close();
            } catch (IOException ioe) {
                System.out.println("IOException: " + ioe.getMessage());
            } catch (SecurityException se) {
                System.out.println("SecurityException: " + se.getMessage());
            } catch (Exception e) {
    
                e.printStackTrace();
            }
            finally
            {
                if(fc!=null)
                {
                    try {
                        fc.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }

        }
        getForm().deleteAll();
        StringItem item = new StringItem("Song's added",""+counter);
        
        getForm().append(item);
    }

    public void commandAction(Command cmnd, Item item) {
        String fileSystem = item.getLabel();
        Form f = this.getForm();
        this.switchDisplayable(null, f);
        f.deleteAll();
        this.fileSystem = fileSystem;
      //  setFileList(fileSystem);
        Thread t = new Thread(this);
        t.start();
    }

    public void run() {
       setFileList(fileSystem);
       startServer();
    }
    
    public void startServer()
    {
        
        Thread t = new Thread()
        {
            public void run()
            {
                while(true)
                {
                    Enumeration e = connections.elements();
                    while(e.hasMoreElements())
                    {
                        WSConnection c = (WSConnection) e.nextElement();
                        if(c.isAlive())
                        {
                            if(System.currentTimeMillis()- c.last >4000l )
                            {
                             
                                if(c.finalizable)
                                    c.interrupt();
                            }
                        }
                        else
                        {
                            connections.removeElement(c);
                            c=null;
                        }
                        try{
                            Thread.sleep(1000l);
                        }
                        catch(Exception ex)
                        {
                            
                        }
                    }
                }
            }
        };
        t.start();
 
        
        try{
          scn =(StreamConnectionNotifier)Connector.open("socket://:80");
          StringItem item = new StringItem("Streaming on..",System.getProperty("microedition.hostname"));
          getForm().append(item);
             while (true) {
                 StreamConnection sc = (StreamConnection)scn.acceptAndOpen();
               //  f.append("sc accepted");
                 // service the connection in a separate thread
                 WSConnection c = new WSConnection(sc,files,images,getForm(),filepool,threadCounter++);
                 
                 c.start();
                 connections.addElement(c);
                 
               
             }


         } catch (IOException e) {
             //Handle Exceptions any other way you like.
             //No-op
             e.printStackTrace();
             getForm().append(""+e.toString());
         }
    }
}
